package com.xiaotu.spider.iqy.pageprocessor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.InflaterInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.TVDanMuCommentModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.KeywordEncode;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.common.util.StringUtil;
import com.xiaotu.spider.APageProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.Html;

/**
 *  爱奇艺弹幕爬取
 * @author wangyanlong
 * @date 2019年7月23日 上午10:55:03
 *
 */
@Component("IQYDanMuPageProcessor")
@Scope("prototype")
public class IQYDanMuPageProcessor extends APageProcessor
{
	
    @Override
    protected Request getStartRequest(JSONObject target)
    {
        return new Request("https://so.iqiyi.com/so/q_"
        		+KeywordEncode.encode(target.getString("tvName"))+"?source=input");
    }

    @Override
    public void process(Page page)
    {
        Map<String, Object> tvMap = page.getRequest().getExtras();
        switch (this.getPageDataType(page))
        {
            case Constants.PageDataType.SEARCH_LIST:
                this.searchListProcess(page, tvMap);
                break;
            case Constants.PageDataType.TV_RECORD:
                this.tvProcess(page,tvMap);
                break;
            default:
                break;
        }
    }

    private void searchListProcess(Page page, Map<String, Object> tvMap){
    	List<String> divList = page.getHtml()
				.xpath("//div[@class='mod_search_result']/div[@class='mod_result']"
						+ "/ul[@class='mod_result_list']/li").all();
		if (divList == null || divList.isEmpty())
			throw new SpiderException(
					SpiderExceptionCode.DataInvalideException);
		
		for (String divStr : divList){
            Html divObj = new Html(divStr);
            String tvName = divObj.xpath("//li[@class='list_item']/@data-widget-searchlist-tvname").get();
            if(StringUtil.isNotEmpty(tvName)){
            	tvName = RegexUtils.regexChStr(tvName).trim();
            }
            String tvType = divObj.xpath("//li[@class='list_item']/@data-widget-searchlist-catageory").get();
            List<String> peopleList = divObj.xpath("//li[@class='list_item']/div/div[@class='info_item'][1]/div").all();
            boolean dirFlage = false;
            boolean actorFlage = false;
            for (String peopleDiv: peopleList) {
				Html peopleObj = new Html(peopleDiv);
				String peopleType = peopleObj.xpath("//div/label[@class='result_info_lbl']/text()").get();
				if(peopleType !=null && peopleType.contains("导演")){
					List<String> directorList = peopleObj.xpath("//div/a").all();
					for (String directorDiv : directorList) {
						Html directorObj = new Html(directorDiv);
						String director = directorObj.xpath("//a/text()").get();
						if(tvMap.get("director").toString().contains(director)){
							dirFlage =true;
							break;
						}
					}
					
				}else if(peopleType !=null && peopleType.contains("主演")){
					List<String> actorList = peopleObj.xpath("//div/a").all();
					for (String actorDiv : actorList) {
						Html actorObj = new Html(actorDiv);
						String actor = actorObj.xpath("//a/text()").get();
						if(tvMap.get("actor").toString().contains(actor)){
							actorFlage =true;
							break;
						}
					}
				}
				
			}
            
            String tvOldName = tvMap.get("tvName")+"";
            if(StringUtil.isNotEmpty(tvOldName)){
            	tvOldName = RegexUtils.regexChStr(tvOldName).trim();
            }
            if(tvOldName.equals(tvName) 
            		&& tvMap.get("tvType").toString().equals(tvType) 
            		&& dirFlage && actorFlage){
            	 List<String> url = divObj.xpath("//li[@class='list_item']//div/div[@class='info_item mt15']/"
            	 		+ "div[@data-tvlist-elem='alllist']/div/ul[@data-tvlist-elem='list']/li[@class='album_item']/a/@href").all();
            	//List<String> url = new ArrayList<String>();
            	//url.add("https://www.iqiyi.com/v_19rs007kqc.html?vfrm=pcw_dianshiju&vfrmblk=B&vfrmrst=fcs_2_p1");
            	 PageUtils.addTargetRequests(page, url, tvMap);
            }
        }
		
    }

    private void tvProcess(Page page, Map<String, Object> tvMap) {
    	String tvId = page.getRawText();
    	tvId = tvId.substring(tvId.indexOf("param['tvid']"), tvId.indexOf("param['vid']"));
    	if(StringUtil.isNotEmpty(tvId)){
    		tvId = RegexUtils.regexSearch(RegexUtils.REGEX_INTEGER, tvId);
    	}
    	if (StringUtil.isEmpty(tvId))
			throw new SpiderException(
					SpiderExceptionCode.DataInvalideException);
    	
    	List<TVDanMuCommentModel> resList = new ArrayList<TVDanMuCommentModel>();
		try {
			List<String> commentList = getDanMu(tvId);
			if(null !=commentList && commentList.size() >0){
				for (String comments : commentList) {
					JSONObject json=xml2JSON(comments.getBytes());
					JSONObject searchJson = JSONObject.fromObject(json);
					JSONArray array = searchJson.getJSONObject("danmu").getJSONArray("data");
					 for (int i = 0; i < array.size(); i++){
						 JSONArray entryArray = array.getJSONObject(i).getJSONArray("entry");
						 for(int j=0;j< entryArray.size();j++){
							 JSONArray listArray = entryArray.getJSONObject(j).getJSONArray("list");
							 for (int y=0;y<listArray.size();y++) {
								 JSONArray bulletInfoArray = listArray.getJSONObject(y).getJSONArray("bulletInfo");
								 for (int k = 0; k < bulletInfoArray.size(); k++) {
									 String contentId = bulletInfoArray.getJSONObject(k).getString("contentId");
									 if(StringUtil.isNotEmpty(contentId)){
										 contentId = contentId.replace("[\"", "").replace("\"]", "");
									 }
									 String content = bulletInfoArray.getJSONObject(k).getString("content");
									 if(StringUtil.isNotEmpty(content)){
										 	content = content.replace("[\"", "").replace("\"]", "");
											content = content.replaceAll("[^(0-9a-zA-Z\u4e00-\u9fa5\\p{P}\r\n )]","");
									}
									 String showTime = bulletInfoArray.getJSONObject(k).getString("showTime");
									 if(StringUtil.isNotEmpty(showTime)){
										 showTime = showTime.replace("[\"", "").replace("\"]", "");
									 }
									 JSONArray userInfoArray = bulletInfoArray.getJSONObject(k).getJSONArray("userInfo");
									 String opername = "";
									 for (int l = 0; l < userInfoArray.size(); l++) {
										 opername = userInfoArray.getJSONObject(l).getString("name");
										 if(opername.contains("null")){
												opername = "";
											}else{
												opername = opername.replace("[\"", "").replace("\"]", "");
												opername = opername.replaceAll("[^(0-9a-zA-Z\u4e00-\u9fa5\\p{P}\r\n )]","");
											}
									}
									 resList.add(new TVDanMuCommentModel(tvMap.get("tvName")+"",
												contentId,opername,content,"",showTime,"","爱奇艺")); 
								}
							}
						 }
					 }
						 page.putField(TVDanMuCommentModel.class.getName(), resList);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	 	
    }
    
    public static List<String> getDanMu(String tvId) {
        // 根据tvId获取电影或者电视剧的详细信息。
        String infoUrl = "http://mixer.video.iqiyi.com/jp/mixin/videos/" + tvId;
        String info = httpGetRequest(infoUrl, false);
        info = info.replace("var tvInfoJs=", "");
        JSONObject jsonObject = JSONObject.fromObject(info);
        // 电影或电视剧专辑
        String albumId = jsonObject.getString("albumId");
        // 电影或电视剧频道
        String channelId = jsonObject.getString("channelId");
        // 电影或电视剧时长
        int duration = jsonObject.getInt("duration");
        return getDanMu(tvId, albumId, channelId, duration);
    }

    private static List<String> getDanMu(String tvId, String albumId, String channelId, int duration) {
        // 弹幕下载地址
        String IQIYI_GET_DANMU_URL = "http://cmts.iqiyi.com/bullet/%s/%s/%s_300_%s.z?rn=%s&business=danmu&is_iqiyi=true&is_video_page=true&tvid=%s&albumid=%s&categoryid=%s&qypid=01010021010000000000";
        List<String> danmus = new ArrayList<String>();
        // 根据电影或电视剧的时长计算出需要多少个批量弹幕请求，爱奇艺平均5分钟请求一次加载弹幕
        int page = duration / (60 * 5) + 1;
        for (int i = 1; i <= page; i++) {
            try {
                String t = "0000" + tvId;
                int length = t.length();
                String first = t.substring(length - 4, length - 2);
                String second = t.substring(length - 2);
                String rn = "0." + randomNum(16);
                String danmuUrl = String.format(IQIYI_GET_DANMU_URL, first, second, tvId, i, rn, tvId, albumId,
                        channelId);
                String res = httpGetRequest(danmuUrl, true);
                if (res != null) {
                    danmus.add(res);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return danmus;
    }

    // httpClient 请求
    private static String httpGetRequest(String url, boolean needUnzip) {
        CloseableHttpClient httpClient = HttpClients.custom().build();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                if (needUnzip) {
                    return new String(decompress(entity.getContent()));
                }
                return EntityUtils.toString(entity);
            }
        } catch (Exception e) {
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 解压缩字节流
    private static byte[] decompress(InputStream is) {
        InflaterInputStream iis = new InflaterInputStream(is);
        ByteArrayOutputStream o = new ByteArrayOutputStream(1024);
        try {
            int i = 1024;
            byte[] buf = new byte[i];
            while ((i = iis.read(buf, 0, i)) > 0) {
                o.write(buf, 0, i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return o.toByteArray();
    }

    // 构造随机参数
    private static String randomNum(double n) {
        double s = Math.pow(10, n - 1);
        double e = Math.pow(10, n) - 1;
        double res = Math.random() * (e - s) + s;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        return nf.format(res);
    }
    
    public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
        JSONObject json = new JSONObject();
        InputStream is = new ByteArrayInputStream(xml);
        SAXBuilder sb = new SAXBuilder();
        org.jdom2.Document doc = sb.build(is);
        Element root = doc.getRootElement();
        json.put(root.getName(), iterateElement(root));
        return json;
    }

    private static JSONObject iterateElement(Element element) {
        List node = element.getChildren();
        Element et = null;
        JSONObject obj = new JSONObject();
        List list = null;
        for (int i = 0; i < node.size(); i++) {
            list = new LinkedList();
            et = (Element) node.get(i);
            if (et.getTextTrim().equals("")) {
                if (et.getChildren().size() == 0)
                    continue;
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(iterateElement(et));
                obj.put(et.getName(), list);
            } else {
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(et.getTextTrim());
                obj.put(et.getName(), list);
            }
        }
        return obj;
    }
    
    @Override
    public String getSpiderType()
    {
        return Constants.SpiderTaskType.IQY_TV_DANMU;
    }

    @Override
    public String getPageDataType(Page page)
    {
        String url = page.getUrl().toString();
        if (url.contains("so.iqiyi.com/so/q_"))
            return Constants.PageDataType.SEARCH_LIST;
        else if (url.contains("www.iqiyi.com/v"))
            return Constants.PageDataType.TV_RECORD;
        return Constants.PageDataType.TV_COMMENT;
    }
    
}
